<script lang="ts">
	import { page } from '$app/state';
	import { USER_TYPE } from '$lib/api/proto/user_api';
	import { userStore } from '$lib/stores/user.svelte';
	import { uniqId } from '$lib/utils/id_utils';

	interface Props {
		onClose: () => void;
	}
	const props: Props = $props();

	let curTab: 'wx' | 'local' = $state(import.meta.env.VITE_WX_APP_ID != undefined ? 'wx' : 'local');

	let userName = $state('');
	let password = $state('');

	function wxAction(divWrap: HTMLDivElement): any {
		$effect(() => {
			window.WxLogin({
				self_redirect: true,
				id: divWrap.id,
				appid: import.meta.env.VITE_WX_APP_ID,
				scope: 'snsapi_login',
				redirect_uri: encodeURIComponent(
					import.meta.env.VITE_WX_REDIRECT_PREFIX +
						`/user/wxcb?from=${encodeURIComponent(page.url.protocol + '//' + page.url.host)}`
				),
				state: uniqId(),
				style: '',
				href: '',
			});
		});
	}

	function onMessage(ev: MessageEvent) {
		if (ev.data.type == 'WxLogin' && typeof ev.data.code == 'string') {
			userStore
				.login({
					userType: USER_TYPE.USER_TYPE_WECHAT,
					userName: '',
					passwdOrCode: ev.data.code as string
				})
				.then(() => {
					props.onClose();
				});
		}
	}

	$effect(() => {
		window.addEventListener('message', onMessage, false);
		return () => {
			window.removeEventListener('message', onMessage, false);
		};
	});
</script>

<dialog class="modal modal-open">
	<div class="modal-box w-[380px]">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onClose()}>✕</button
		>
		<h3 class="text-lg font-bold">登录</h3>
		{#if import.meta.env.VITE_WX_APP_ID != undefined}
			<div role="tablist" class="tabs tabs-lift">
				<button
					role="tab"
					class="tab {curTab == 'wx' ? 'tab-active' : ''}"
					onclick={() => (curTab = 'wx')}>微信</button
				>
				{#if curTab == 'wx'}
					<div class="tab-content border-base-300 bg-base-100 p-4" id="wx_login" use:wxAction></div>
				{/if}
				<button
					role="tab"
					class="tab {curTab == 'local' ? 'tab-active' : ''}"
					onclick={() => (curTab = 'local')}>账号密码</button
				>
				{#if curTab == 'local'}
					<div class="tab-content border-base-300 bg-base-100 p-4 flex-col space-y-4">
						<label class="label w-full">
							<span class="label w-[60px] text-right inline-block pr-[10px]">账号:</span>
							<input type="text" class="input w-full" bind:value={userName} />
						</label>
						<label class="label w-full">
							<span class="label w-[60px] text-right inline-block pr-[10px]">密码:</span>
							<input type="password" class="input w-full" bind:value={password} />
						</label>
						<div class="modal-action">
							<button class="btn" onclick={() => props.onClose()}>取消</button>
							<button
								class="btn btn-primary"
								disabled={userName.trim() == '' || password.trim() == ''}
								onclick={() =>
									userStore
										.login({
											userType: USER_TYPE.USER_TYPE_LOCAL,
											userName: userName,
											passwdOrCode: password
										})
										.then(() => props.onClose())}>登录</button
							>
						</div>
					</div>
				{/if}
			</div>
		{/if}
	</div>

	<div class="modal-backdrop">
		<button onclick={() => props.onClose()}>close</button>
	</div>
</dialog>
